package com.dmyang.controller;

import com.dmyang.common.pojo.HyResult;
import com.dmyang.common.utils.CookieUtils;
import com.dmyang.entity.HyUser;
import com.dmyang.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by brss on 2017/8/8.
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 跳转到用户登录界面
     * @return
     */
    @RequestMapping("/login")
    public String login(){return "adminLogin";}

    /**
     * 检查用户登录信息是否正确
     * @return
     */
    @RequestMapping("/loginCheck")
    @ResponseBody
    public HyResult loginCheck(HyUser user,String checkCode, HttpServletRequest request){
        //判断验证码是否正确
        String jsessionid = CookieUtils.getCookieValue(request, "JSESSIONID");
        String code= (String) request.getSession().getAttribute(jsessionid);
        if (StringUtils.isBlank(code)){
            return HyResult.build(500,"错误：无法获取到你的信息，请刷新！");
        }
        if (!code.equals(checkCode)){
            return HyResult.build(500,"验证码不正确!");
        }
        //验证成功后，删除sesson
        request.getSession().removeAttribute(jsessionid);
        //调用Service，插入数据
        try {
            HyUser result = userService.checkUserLogin(user);
            if (result.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))){
                request.getSession().setAttribute("userinfo",user);
                return HyResult.build(200,"登录成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return HyResult.build(500,"登录失败，服务器错误！");
        }
        return HyResult.build(500,"登录失败，用户名或者密码不正确！");
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        request.getSession().removeAttribute("userinfo");
        return "adminLogin";
    }
}
